<?php
namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use service\ToolsService;
use think\Db;
use think\exception\HttpResponseException;
use think\facade\Cache;

/**
 * banner管理
 */
class Banner extends BasicAdmin
{

    public $banner = 'tp_banner';
    /**
     * banner管理
     * @return array|string
     */
    public function lists()
    {
        $this->title = 'banner管理';
        $get = $this->request->get();
        $db = Db::name($this->banner);

        foreach (['title'] as $field) {
            if(isset($get[$field]) && $get[$field] !== '') {
                $db->whereLike($field, "%{$get[$field]}%");
            }
        }

        if (isset($get['create_at']) && $get['create_at'] !== '') {
            list($start, $end) = explode(' - ', $get['create_at']);
            $db->whereBetween('create_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
        }

        if ($this->request->isPost()) {
            Cache::store('redis')->handler()->del('vote:banner');
        }

        return parent::_list($db->order('sort desc,id desc'));
    }


    /**
     * 添加Banner
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function add()
    {
        if (!$this->request->isPost()) {
            $this->title = '添加Banner';
            return $this->_form($this->banner, 'form');
        }
        try {
            $data = $this->_form_build_data();
            Db::transaction(function () use ($data) {
                Db::name($this->banner)->insertGetId($data['main']);

            });
        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('Banner添加失败，请稍候再试！');
        }
        list($base, $spm, $url) = [url('@admin'), $this->request->get('spm'), url('banner/lists')];
        Cache::store('redis')->handler()->del('vote:banner');
        $this->success('添加Banner成功！', "{$base}#{$url}?spm={$spm}");
    }

    /**
     * 编辑Banner
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        if (!$this->request->isPost()) {
            $banner_id = $this->request->get('id');
            $banner = Db::name($this->banner)->where(['id' => $banner_id])->find();
            empty($banner) && $this->error('需要编辑的Banner不存在！');
            return $this->fetch('form', ['vo' => $banner, 'title' => '编辑Banner']);
        }
        try {
            $data = $this->_form_build_data();
            $banner_id = $this->request->post('id');
            $banner = Db::name($this->banner)->where(['id' => $banner_id])->find();
            empty($banner) && $this->error('编辑Banner失败，请稍候再试！');

            Db::transaction(function () use ($data, $banner_id, $banner) {
                // 更新产品主表
                $where = ['id' => $banner_id];
                Db::name($this->banner)->where($where)->update(array_merge($banner, $data['main']));

            });
            Cache::store('redis')->handler()->del('vote:banner');
        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('编辑Banner失败，请稍候再试！' . $e->getMessage());
        }
        list($base, $spm, $url) = [url('@admin'), $this->request->get('spm'), url('banner/lists')];
        $this->success('编辑Banner成功！', "{$base}#{$url}?spm={$spm}");
    }


    /**
     * 读取POST表单数据
     * @return array
     */
    protected function _form_build_data()
    {
        list($main, $list, $post, $verify) = [[], [], $this->request->post(), false];
        empty($post['pic']) && $this->error('Banner图片不能为空，请上传后再提交数据！');
        // Banner主数据组装
        $main['title'] = $this->request->post('title', '');
        $main['pic'] = $this->request->post('pic', '');
        $main['url'] = $this->request->post('url', '');
        return ['main' => $main, 'list' => $list];
    }

    /**
     * 删除Banner
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del()
    {
        if (DataService::update($this->banner)) {
            Cache::store('redis')->handler()->del('vote:banner');
            $this->success("Banner删除成功！", '');
        }
        $this->error("Banner删除失败，请稍候再试！");
    }

    /**
     * 取消Banner显示/置顶
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbid()
    {
        if (DataService::update($this->banner)) {
            Cache::store('redis')->handler()->del('vote:banner');
            $this->success("Banner关闭显示成功！", '');
        }
        $this->error("Banner关闭显示失败，请稍候再试！");
    }

    /**
     * Banner显示/置顶
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resume()
    {
        if (DataService::update($this->banner)) {
            Cache::store('redis')->handler()->del('vote:banner');
            $this->success("Banner启动显示成功！", '');
        }
        $this->error("启动显示失败，请稍候再试！");
    }

}
